package com.itboye.lottery.base

import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.itboye.bylibrary.dialog.LoadingDialog
import com.itboye.lottery.annotions.IsNeedClick
import com.itboye.lottery.widget.titlebarwidget.TitleBarStyleUtil
import com.itboye.lottery.widget.titlebarwidget.TranslucentActionBar

/**
 * Created by Administrator on 2017/11/28.
 */
abstract class BaseFragment : Fragment(), View.OnClickListener {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(getLayoutId(), null)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        smartInject()
        initData()
    }


    var dialog: LoadingDialog? = null
    fun showDialog() {
        try {
            if (activity!!.isFinishing) return
            if (dialog == null) {
                dialog = LoadingDialog(activity)
            }
            dialog!!.show()
        }catch (e:Exception){
            e.printStackTrace()
        }
    }

    fun dissDialog() {
        if (dialog != null) {
            dialog!!.dismiss()
            dialog = null
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        dissDialog()
    }

    fun smartInject() {
        try {
            var clz: Class<out Fragment> = javaClass

            while (clz != BaseFragment::class.java) {

                val fs = clz.declaredFields
                val res = resources
                val packageName = activity!!.packageName
                for (field in fs) {
                    if (!View::class.java.isAssignableFrom(field.type)) {
                        continue
                    }
                    val viewId = res.getIdentifier(field.name, "id",
                            packageName)
                    if (viewId == 0)
                        continue
                    field.isAccessible = true
                    try {
                        val v = view!!.findViewById<View>(viewId)
                        field.set(this, v)
                        val c = field.type
                        //判断是否有注解
                        if (field.annotations != null) {
                            if (field.isAnnotationPresent(IsNeedClick::class.java)) {//如果属于这个注解
                                //为这个控件设置属性
                                field.isAccessible = true//允许修改反射属性
                                val inject = field.getAnnotation(IsNeedClick::class.java)
                                //                                int value=inject.value();//得到注解的值
                                //                                if(value==-1){
                                //
                                //                                }
                            } else {
                                val m = c.getMethod("setOnClickListener",
                                        View.OnClickListener::class.java)
                                m.invoke(v, this)
                            }
                        } else {
//                            val m = c.getMethod("setOnClickListener",
//                                    View.OnClickListener::class.java)
//                            m.invoke(v, this)
//                                                        Method m = c.getMethod("setOnClickListener",
//                                                                View.OnClickListener.class);
//                                                        m.invoke(v, this);
                        }
                    } catch (e: Throwable) {
                    }

                    field.isAccessible = false

                }

                clz = clz.superclass as Class<out Fragment>

            }
        } catch (e: Exception) {
            // TODO Auto-generated catch block
            e.printStackTrace()
        }


    }


    fun actionbarSet(actionBar: TranslucentActionBar, title: String, leftIcon: Int, strLeft: String, rightIcon: Int, strRight: String, listener: View.OnClickListener) {
        TitleBarStyleUtil.initTitlebarStyle(actionBar, title, leftIcon, strLeft, rightIcon, strRight, listener)
    }

//    private val PERMISSION_REQUESTCODE = 100
//    private lateinit var mListener: PermissionListener
//    fun requestRunPermisssion(permissions: Array<String>, listener: PermissionListener) {
//        mListener = listener
//        val permissionLists = ArrayList<String>()
//        for (permission in permissions) {
//            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
//                permissionLists.add(permission)
//            }
//        }
//
//        if (!permissionLists.isEmpty()) {
//            ActivityCompat.requestPermissions(activity, permissionLists.toTypedArray(), PERMISSION_REQUESTCODE)
//        } else {
//            //表示全都授权了
//            mListener.onGranted()
//        }
//    }

//    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//        when (requestCode) {
//            PERMISSION_REQUESTCODE -> if (grantResults.size > 0) {
//                //存放没授权的权限
//                val deniedPermissions = ArrayList<String>()
//                for (i in grantResults.indices) {
//                    val grantResult = grantResults[i]
//                    val permission = permissions[i]
//                    if (grantResult != PackageManager.PERMISSION_GRANTED) {
//                        deniedPermissions.add(permission)
//                    }
//                }
//                if (deniedPermissions.isEmpty()) {
//                    //说明都授权了
//                    mListener.onGranted()
//                } else {
//                    mListener.onDenied(deniedPermissions)
//                }
//            }
//            else -> {
//            }
//        }
////    }

    fun showPermission(activity: Activity) {
        //当拒绝了授权后，为提升用户体验，可以以弹窗的方式引导用户到设置中去进行设置
        AlertDialog.Builder(activity)
                .setMessage("需要开启权限才能使用此功能")
                .setPositiveButton("设置", DialogInterface.OnClickListener { dialog, which ->
                    //引导用户到设置中去进行设置
                    val intent = Intent()
                    intent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
                    intent.data = Uri.fromParts("package", activity.packageName, null)
                    startActivity(intent)
                })
                .setNegativeButton("取消", null)
                .create()
                .show()
    }

//    override fun onResume() {
//        // TODO Auto-generated method stub
//        super.onResume()
//        MobclickAgent.onResume(activity)
//    }
//
//    override fun onPause() {
//        // TODO Auto-generated method stub
//        super.onPause()
//        MobclickAgent.onPause(activity)
//    }


    protected abstract fun getLayoutId(): Int

    protected abstract fun initData()
}